﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Microsoft.Practices.Unity;
using EPlanet.Web.UI.WebControls;
using Web.SystemConfig.Business;
using Web.SystemConfig.Services;

using DreamBuilder.UI.UserControls;
using DreamBuilder.Core.Message;
using CommonModule;
using DreamBuilder.Core.Container;
using DreamBuilder.Core.Log;
using Web.SystemLogin.Business;
using System.Threading;
using Web.Views.Public;

namespace Web.Views.SystemConfig
{
    public partial class  Auth_OrgEdit: PageBase
    {
        #region 控件及变量定义
        /// <summary>
        /// Business类
        /// </summary>

        [Dependency]
        public IAuth_Org Auth_OrgComponent
        {
            get;
            set;
        }
        [Dependency]
        public IAuth_User Auth_UserComponent
        {
            get;
            set;
        }
        #endregion

        #region PageLoad方法

        private void Page_Load(object sender, System.EventArgs e)
        {
            SetPageProperty();
            InitControlsCultureInfo();
            if (!IsPostBack)
            {    
                Auth_OrgComponent.LoadCheckBoxList(this.cblRole);
                this.cblRole.RepeatColumns = 3;
                ShowEdit();
                //ShowCbkRole();
            }
            CreateToolMenu(Toolbar1, ToolMenuType.TYPE_Edit);
            SetToolBarVisible();
            base.CheckEditAuthorities(base.CurrentPageState);
        }

        /// <summary>
        /// 设置页面的菜单属性
        /// </summary>
        private void SetPageProperty()
        {
            this.DBHelpName = DBHelperString.Dictionary;
            base.MenuID = "ePlanet.Configuration.Auth_Org";
            if (!IsPostBack)
            {
                if ((Request["pkValue"] == null || Request["pkValue"].Trim().Length == 0))
                {
                    base.CurrentPageState = PageState.State_New;
                }
                else
                {
                    base.CurrentPageState = PageState.State_Edit;
                    base.PKValue = Request.QueryString.Get("pkValue");
                }
            }
        }

        /// <summary>
        /// 显示列表,为列表控件的单据id赋值
        /// </summary>
        private void ShowEdit()
        {
            ucedit.VoucherID = "vch_Auth_ORG";
            ucedit.PKValue = base.PKValue;
        }
        ///<summary>
        ///显示权限
        ///</summary>
        private void ShowCbkRole()
        {
            if (Request.QueryString["pkValue"] != null)
            {
                Auth_OrgComponent.SetCheckBoxList(this.cblRole, Request.QueryString["pkValue"]);
            }
        }

        /// <summary>
        /// 初始化控件多语信息
        /// </summary>
        private void InitControlsCultureInfo()
        {
            this.TabControl1.Items[0].Caption = GetString("Auth_OrgEdit");
            this.litOrgRole.Text = GetString("OrgRole");
        }

        private void SetToolBarVisible()
        {
            if (!string.IsNullOrEmpty(Request.QueryString["FirstEdit"]))
            {
                ToolBarHelper.SetToolBarVisible(Toolbar1, ToolBarID.Cancel, false);
            }
            else
            {

            }
        }

        #endregion

        #region OnPreRender方法

        /// <summary>
        /// 重写OnPreRender方法
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreRender(EventArgs e)
        {
            //设置组织机构的上级机构
            SetParentID();
            base.OnPreRender(e);
            //设置组织机构默认的编码
            SetOrgCode();
            //设置组织机构默认状态为历史状态
            SetOrgStatus();
        }

        private void SetParentID()
        {
            RefEditor refParentID = this.ucedit.FindControl(this.ucedit.GetEditControlID("P_Auth_ORG", "Parent_ID")) as RefEditor;
            //设置ID
            if (refParentID != null&& !string.IsNullOrEmpty(Request.QueryString.Get("Parent_ID")))
            {
                refParentID.RefCodeValue = Request.QueryString.Get("Parent_ID").ToString();
                refParentID.SetRefNameText();
            }
        }

        private void SetOrgCode()
        {
            if (string.IsNullOrEmpty(this.PKValue))
            {
                TextBox txtORG_Code = this.ucedit.FindControl(this.ucedit.GetEditControlID("P_Auth_ORG", "ORG_Code")) as TextBox;
                //设置ID
                if (txtORG_Code != null)
                {
                    txtORG_Code.Text = (Auth_OrgComponent.GetMaxOrgCode() + 1).ToString();
                }
            }
        }

        private void SetOrgStatus()
        {
            if (string.IsNullOrEmpty(this.PKValue))
            {
                RadioButtonList rblStatus = this.ucedit.FindControl(this.ucedit.GetEditControlID("P_Auth_ORG", "Status")) as RadioButtonList;
                //设置ID
                if (rblStatus != null)
                {
                    rblStatus.SelectedIndex = rblStatus.Items.Count - 1;
                }
            }
        }

        #endregion


        #region 事件处理方法
        /// <summary>
        /// 工具条事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Toolbar1_MenuItemClick(object sender, MenuItemClickEventArgs e)
        {
            switch (e.EventItem.ID.ToString().ToLower())
            {
                case "tbsave":
                    this.Validate();
                    if (this.IsValid)
                    {
                        OnSaveData();
                    }
                    break;
                case "tbcancel":
                    RedirectList(Request.QueryString.Get("Parent_ID").ToString());
                    break;
                case "tbhelp":
                    break;
            }
        }
        #endregion

        #region 保存
        /// <summary>
        /// 保存数据
        /// </summary>
        private void OnSaveData()
        {
            //构建DataSet
            System.Data.DataSet dsInfo = new System.Data.DataSet();
            //取主表，存主表
            dsInfo.Tables.Add(ucedit.GetEditDataTable());
            string mainKey = dsInfo.Tables[0].Rows[0][0].ToString();
            string pkName = dsInfo.Tables[0].Rows[0]["P_Auth_ORG.ORG_Name"].ToString();
            if (dsInfo != null)
            {
                //by lyn 20111020                            
                if (String.IsNullOrEmpty(Request.QueryString["pkValue"].ToString()))
                {
                    string checkOrgCode = dsInfo.Tables[0].Rows[0]["P_Auth_ORG.ORG_Code"].ToString();
                    bool checkOrg = Auth_OrgComponent.CheckORG_Code(checkOrgCode);
                    if (checkOrg == false)
                    {
                        this.ShowMsg("此单位编号已存在，请更改单位编号。");
                        DisplayMessage("此单位编号已存在，请更改单位编号。");
                        return;
                    }
                }
                else
                {
                    string checkStatus = dsInfo.Tables[0].Rows[0]["P_Auth_ORG.Status"].ToString();
                    if (checkStatus == "Org_Status--0")
                    {
                        bool checkHistoryORG = Auth_OrgComponent.checkHistoryORG(Request.QueryString["pkValue"].ToString());
                        if (checkHistoryORG == false)
                        {
                            this.ShowMsg("该单位不能改为历史单位！！");
                            DisplayMessage("该单位不能改为历史单位！！");
                            return;
                        }
                    }

                }
                dsInfo.Tables[0].Rows[0]["P_Auth_ORG.Status"] = "Org_Status--1";
                ResultInfo result = Auth_OrgComponent.SaveEditDataAndCblData(dsInfo, this.cblRole);
                // ResultInfo result = Auth_OrgComponent.Save(dsInfo);
                if (result.bSuccess == true)
                {
                    if (!string.IsNullOrEmpty(Request.QueryString["FirstEdit"]))
                    {
                        if ((Request["pkValue"] == null || Request["pkValue"].Trim().Length == 0))
                        {
                            Auth_UserComponent.ModifyUser("P_Auth_ORG", "Create_User", this.CurrentUser.User_ID, "Create_Time", DateTime.Now, "ORG_ID", mainKey);
                            Auth_UserComponent.ModifyUser("P_Auth_ORG", "Modify_User", this.CurrentUser.User_ID, "Modify_Time", DateTime.Now, "ORG_ID", mainKey);
                            string operationMessage = this.CurrentUser.Real_Name + "新增了" + pkName + "[" + mainKey + "]单位";
                            WriteUserLog(operationMessage,OracleLogType.System);
                        }
                        else
                        {
                            Auth_UserComponent.ModifyUser("P_Auth_ORG", "Modify_User", this.CurrentUser.User_ID, "Modify_Time", DateTime.Now, "ORG_ID", mainKey);
                            string operationMessage = this.CurrentUser.Real_Name + "修改了" + pkName + "[" + mainKey + "]单位";
                            WriteUserLog(operationMessage,OracleLogType.System);
                        }
                        RedirectList(Request.QueryString.Get("pkValue").ToString());
                    }
                    else
                    {
                        //DisplayMessage(result.ErrorDesc);
                        RedirectList(Request.QueryString.Get("pkValue").ToString());
                    }
                }
            }
        }


        #endregion

        #region 页面跳转
        /// <summary>
        /// 跳转到列表页面
        /// </summary>
        private void RedirectList(string Parent_ID)
        {
            if (!string.IsNullOrEmpty(Request.QueryString.Get("Parent_ID").ToString()))
            {
                Parent_ID = Request.QueryString.Get("Parent_ID").ToString();
                Response.Redirect("Auth_Org.aspx?Parent_ID=" + Parent_ID + "&RefreshTree=1");
            }
            else
            {
                Response.Redirect("Auth_Org.aspx?RefreshTree=1");
            }
        }
        #endregion

        #region OnInit
        override protected void OnInit(EventArgs e)
        {
            //
            //CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
            //
            InitializeComponent();
            base.OnInit(e);
        }
        /// <summary>
        /// 添加页面及控件事件
        /// </summary>
        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
            this.Toolbar1.MenuItemClick += new EPlanet.Web.UI.WebControls.MenuItemClickedEventHandler(Toolbar1_MenuItemClick);
        }
        #endregion

        #region 判断是否有上级部门
        private void IsUpDept()
        {
            //if()
        }
        #endregion
    }
}
